package com.forte.controller;

import java.util.List;

import javax.validation.Valid;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.forte.model.LoginModel;
import com.forte.productdao.Product;
import com.forte.productservice.ProductService;
import com.forte.shoppingcustomer.ShoppingCustomerService;
import com.forte.shoppingcustomerdao.ShoppingCustomer;

@Controller
public class LoginController {
	
	
	
	private static final String LOGIN_VIEW_MODEL = "login";
	
	@Autowired
	ShoppingCustomerService customerService;
	
	@Autowired
	ProductService productService;
		
	@RequestMapping(value="/login.do", method = RequestMethod.GET)
	public String login(Model model){
		
		model.addAttribute("login", new LoginModel());
		return "login";
	}
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST )
	public String login(@Valid LoginModel login, BindingResult result, Model model){
		String returnPage = "login";
		ShoppingCustomer customer;
			if(login != null) {
				customer = customerService.findCustomerByEmailAndPassword(login.getemail(), login.getpassword());
						if(customer != null) {
						customer.setPassword(null);
						model.addAttribute("customer", customer);
						//session.setAttribute("username", customer.getFirstName());
						
						returnPage = "product";
					}else{
						result.addError(new FieldError(LOGIN_VIEW_MODEL, "email", "Login Failed. Cannot Find Customer. Try Correct Email and Password"));
					}
			}
			else{
				result.addError(new FieldError(LOGIN_VIEW_MODEL, "email", "Login Failed. Try Correct Email and Password"));
			}
			
//			 List<Product> products = productService.findAllProduct();
//			 model.addAttribute("products", products);
			 LogManager.getRootLogger().log(Level.INFO, "Listing contents of product table");
		  return returnPage;
	}

}
